package com.localking.algorithm.leetcode.array.string

/**
 * Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
 *
 * Example:
 * Input: [0, 1, 0, 3, 12]
 * Output: [1, 3, 12, 0, 0]
 *
 * Note:
 * 1. You must do this in-place without making a copy of the array.
 * 2. Minimize the total number of operations.
 *
 * @author jinbo
 */
object MoveZeros {
  def main(args: Array[String]): Unit = {
    val nums = Array(0, 1, 0, 3, 12)
    moveZeros(nums)
    println(nums.mkString("[", ",", "]"))
  }

  def moveZeros(nums: Array[Int]): Unit = {
    var zeroStartIndex = 0
    var zeroEndIndex = 0
    var findZero = false
    for (i <- nums.indices) {
      if (nums(i) == 0) {
        if (!findZero) {
          findZero = true
          zeroStartIndex = i
          zeroEndIndex = i
        } else {
          zeroEndIndex += 1
        }
      } else {
        if (findZero) {
          nums.update(zeroStartIndex, nums(i))
          nums.update(i, 0)
          zeroStartIndex += 1
          zeroEndIndex += 1
        }
      }
    }
  }
}
